//
//  WTDetailViewController.m
//  CoreDataContact
//
//  Created by 王婷 on 15/11/21.
//  Copyright © 2015年 王婷. All rights reserved.
//

#import "WTDetailViewController.h"
#import "WTCoreDataManager.h"
#import "Entity.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

@interface WTDetailViewController ()<BMKMapViewDelegate, BMKLocationServiceDelegate, BMKPoiSearchDelegate, BMKGeoCodeSearchDelegate>
{
    BMKPoiSearch *_poisearch;
    BMKMapView *_mapView;
    BMKLocationService *_locService;
    bool isGeoSearch;
}



- (IBAction)Save:(id)sender;
@property(nonatomic, strong)WTCoreDataManager *manager;
@property(nonatomic, strong)BMKPointAnnotation *pointAnnotation;
@property(nonatomic, strong)BMKGeoCodeSearch *geocodesearch;

- (IBAction)alter:(id)sender;


@end

@implementation WTDetailViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _locService.delegate = self;
    _poisearch.delegate = self;
    _geocodesearch.delegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 300, self.view.frame.size.width, 300)];
    [self.view addSubview: _mapView];
    
//    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0) {
//        self.navigationController.navigationBar.translucent = NO;
        // 初始化BMKLocationService
//        _locService = [[BMKLocationService alloc]init];
//        _locService.delegate = self;
//        // 启动LocationService
//        [_locService startUserLocationService];
//        _mapView.showsUserLocation = NO;
//        _mapView.userTrackingMode = BMKUserTrackingModeNone;
//        _mapView.showsUserLocation = YES;
    
    _poisearch = [[BMKPoiSearch alloc]init];
    [_mapView setZoomLevel:13];
    _mapView.isSelectedAnnotationViewFront = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(lpngPress:)];
    [_mapView addGestureRecognizer:longPress];
    
//    }
    
    
//    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
//    citySearchOption.pageIndex = 0;
//    citySearchOption.pageCapacity = 10;
//    citySearchOption.city = self.nativeTextField.text;
//    citySearchOption.keyword = nil;
//    BOOL flag = [_poisearch poiSearchInCity:citySearchOption];
//    if (flag) {
//        NSLog(@"城市内检索发送成功");
//    } else {
//        NSLog(@"城市内检索发送失败");
//    }
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    NSString *oreillyAddress = self.per.native;
#pragma mark apple提供的方法 方向地理编码
    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
    [myGeocoder geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0 && error == nil)
        {
            NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
            NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
            NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
            
            if (self.pointAnnotation == nil) {
                self.pointAnnotation = [[BMKPointAnnotation alloc] init];
                CLLocationCoordinate2D coor;
                coor.latitude = firstPlacemark.location.coordinate.latitude;
                coor.longitude = firstPlacemark.location.coordinate.longitude;
                self.pointAnnotation.coordinate = coor;
                self.pointAnnotation.title = self.per.native;
                _mapView.centerCoordinate = coor;
                
            }
            
            [_mapView addAnnotation:self.pointAnnotation];
            
            
        }
        else if ([placemarks count] == 0 && error == nil)
        {
            NSLog(@"Found no placemarks.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    
    
    
    self.nameTextField.text = self.per.name;
    self.sexTextField.text = self.per.sex;
    self.numberTextField.text = self.per.number.stringValue;
    self.phoneTextField.text = self.per.phone.stringValue;
    self.qqTextField.text = self.per.qq.stringValue;
    self.nativeTextField.text = self.per.native;

    self.manager = [WTCoreDataManager shareDefaults];
    NSLog(@"url == %@", [self.manager applicationDocumentsDirectory]);
    [self.manager applicationDocumentsDirectory];

}

#pragma mark -- BMKMapViewDelegate

//- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
//    // 生成重用标志identifier
//    NSString *AnnotationViewID = @"map";
//    // 检查时候有重用的缓存
//    BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
//    // 缓存没有命中, 自己构造一个, 一般首次添加annotation代码会运行到此处
//    if (annotationView == nil) {
//        annotationView = [[BMKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
////        ((BMKPinAnnotationView *)annotationView).pinColor = BMKPinAnnotationColorRed;
//
//        // 设置重天上掉下的效果(annotation)
//        ((BMKPinAnnotationView *)annotationView).animatesDrop = YES;
//    }
//    // 设置位置
////    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
//    annotationView.annotation = annotation;
//    // 单击弹出泡泡, 弹出泡泡前提annotation必须实现title属性
//    annotationView.canShowCallout = YES;
//    // 设置是否可以拖拽
//    annotationView.draggable = YES;
//    NSLog(@"!!!!!!!!!%f", self.pointAnnotation.coordinate.latitude);
//    return annotationView;
//}


- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //普通annotation
    NSString *AnnotationViewID = @"renameMark";
    BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        // 设置颜色
        annotationView.pinColor = BMKPinAnnotationColorPurple;
        // 从天上掉下效果
        annotationView.animatesDrop = YES;
        // 设置可拖拽
        annotationView.draggable = YES;
        
        NSLog(@"!!!!!!!!!%f", self.pointAnnotation.coordinate.latitude);
    }
    return annotationView;
    
    
}

- (void)lpngPress:(UILongPressGestureRecognizer *)press {
    
    //判断 状态 长按有 两个状态 开始状态 长按结束状态
    if (press.state == UIGestureRecognizerStateEnded) {
        
        //长按结束增加大头针
        BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
        //获取点击的 坐标 -> 相对的图的视图坐标
        CGPoint point = [press locationInView:_mapView];
        
        //把这个坐标 转化为 相对于地图的真正经纬度
        annotation.coordinate = [_mapView convertPoint:point toCoordinateFromView:_mapView];
        
        //实际上应该根据经纬度 进行地理反编码得到 地址最为大头针数据
        
        annotation.title = [NSString stringWithFormat:@"%f", annotation.coordinate.longitude];
        
        //增加到视图上
        [_mapView addAnnotation:annotation];
        
        isGeoSearch = false;
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){annotation.coordinate.latitude, annotation.coordinate.longitude};
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }
        
        
        
    }
    
}

-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        NSString* titleStr;
        NSString* showmeg;
        titleStr = @"反向地理编码";
        showmeg = [NSString stringWithFormat:@"%@",item.title];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:titleStr message:showmeg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        [alertController addAction:action];
        
        [self presentViewController:alertController animated:YES completion:^{
            //
            self.nativeTextField.text = item.title;
            
        }];
        
        
        // 获取查询数据的请求,相当于数据库的查询语句
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Entity"];
        // 添加一个约束 谓词
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"native", @"%@"], self.per.native];
        //给请求添加约束
        request.predicate = predicate;
        
        NSError *error;
        
        NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
        
        NSLog(@"%@", result.address);
        
        //先进行查找在修改
        for (Entity *add in array) {
            add.native = result.address;
        }
        
        [self.manager saveContext];
        NSLog(@"%@", array);
        
        
//        [self.delegate changValue:result.address];
        
        
    }
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}

- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    NSLog(@"didAddAnnotationViews");
}

#pragma mark -- BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode {
    // 清楚屏幕中所有的annotation
    NSArray *array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < poiResult.poiInfoList.count; i++) {
            BMKPoiInfo *poi = [poiResult.poiInfoList objectAtIndex:i];
            BMKPointAnnotation *item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            [annotations addObject:item];
        }
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:annotations animated:YES];
    } else if (errorCode == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR) {
        NSLog(@"起始点有歧义");
    } else {
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)Save:(id)sender {
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:self.manager.managedObjectContext];
    Entity *per = [[Entity alloc]initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
    per.name = self.nameTextField.text;
    per.sex = self.sexTextField.text;
    per.number = @(self.numberTextField.text.integerValue);
    per.native = self.nativeTextField.text;
    per.phone = @(self.phoneTextField.text.integerValue);
    per.qq = @(self.qqTextField.text.integerValue);
    per.flag = @"1";
    [self.manager saveContext];
}



- (IBAction)alter:(id)sender {
    Entity *per = self.per;
    per.name = self.nameTextField.text;
    per.sex = self.sexTextField.text;
    per.number = @(self.numberTextField.text.integerValue);
    per.native = self.nativeTextField.text;
    per.phone = @(self.phoneTextField.text.integerValue);
    per.qq = @(self.qqTextField.text.integerValue);
    per.flag = @"1";
    [self.manager saveContext];
}

- (void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    _locService.delegate = nil;
    _poisearch.delegate = nil;
    _geocodesearch .delegate = nil;
}

#pragma mark -- 地图将要定位
- (void)willStartLocatingUser {
    
}

#pragma mark -- 用户方向更新后
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation {
    [_mapView updateLocationData:userLocation];
    
}

#pragma mark -- 用户位置更新后
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    [_mapView updateLocationData:userLocation];
}

#pragma mark -- 用户停止定位
- (void)didStopLocatingUser {
    
}

#pragma mark -- 定位失败
- (void)didFailToLocateUserWithError:(NSError *)error {
    
}

@end
